<?php

namespace App\Library\Traits;

use Illuminate\Database\Eloquent\Model;
use Yansongda\Artful\Exception\ContainerException;
use Yansongda\Artful\Exception\InvalidParamsException;
use Yansongda\Artful\Exception\ServiceNotFoundException;
use Yansongda\Artful\Rocket;
use Yansongda\Pay\Pay;
use Yansongda\Supports\Collection;

trait AlipayPaymentTrait
{
    /**
     * @throws ServiceNotFoundException
     * @throws ContainerException
     * @throws InvalidParamsException
     */
    public static function withdraw(Model $withdraw): void
    {
        self::withdrawCom($withdraw, Pay::alipay()->transfer([
            'out_biz_no' => $withdraw->serial_number,
            'trans_amount' => (string)$withdraw->amount,
            'product_code' => 'TRANS_ACCOUNT_NO_PWD',
            'biz_scene' => 'DIRECT_TRANSFER',
            'remark' => '提现',
            'payee_info' => [
                'identity' => $withdraw->identity,
                'identity_type' => 'ALIPAY_LOGON_ID',
                'name' => $withdraw->name,
            ],
        ]));
    }

    /**
     * withdrawTest
     * @throws ServiceNotFoundException
     * @throws ContainerException
     * @throws InvalidParamsException
     */
    public static function withdrawTest(Model $withdraw): void
    {
        self::withdrawCom($withdraw, Pay::alipay()->transfer([
            'out_biz_no' => $withdraw->serial_number,
            'trans_amount' => '0.1',
            'product_code' => 'TRANS_ACCOUNT_NO_PWD',
            'biz_scene' => 'DIRECT_TRANSFER',
            'remark' => '提现',
            'payee_info' => [
                'identity' => '2842733316@qq.com',
                'identity_type' => 'ALIPAY_LOGON_ID',
                'name' => '杨杰',
            ],
        ]));
    }

    /**
     * @throws ServiceNotFoundException
     * @throws ContainerException
     * @throws InvalidParamsException
     */
    private static function withdrawCom(Model $withdraw, Collection|Rocket $result): void
    {
        if ($result->status === 'SUCCESS') {
            $withdraw->status_arrival = true;
            $withdraw->pay_at = $result->trans_date;
        }
        $withdraw->result = $result;
        $withdraw->find = Pay::alipay()->query([
            '_action' => 'transfer',
            'product_code' => 'TRANS_ACCOUNT_NO_PWD',
            'biz_scene' => 'DIRECT_TRANSFER',
            'out_biz_no' => $withdraw->serial_number,
        ]);
        $withdraw->save();
    }
}
